//
//  XDVerifiedViewController.m
//  xindailianmeng
//
//  Created by 张东 on 2017/2/23.
//  Copyright © 2017年 xindailianmeng.cn. All rights reserved.
//

#import "XDSetSafePassViewController.h"
#import "ZHRTRequestFailureShowViewOrDetail.h"
#import "ZHRTBasicMethod.h"
#import "AFHTTPSessionManager+POST.h"
#import "XDBindBankCardViewController.h"
#import "XDToWithdrawViewController.h"
#import "XDVerifiedViewController.h"
#import "XDUserCenterController.h"
#define kAlphaNum @"0123456789"
@interface XDSetSafePassViewController ()

@property (nonatomic,weak) UITextField *passTf;
@property (nonatomic,weak) UITextField *passAgainTf;
@property (nonatomic, weak) UIButton *nextBtn;

@end

@implementation XDSetSafePassViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"设置交易密码";
    [self setUI];
    [self.passTf becomeFirstResponder];
}



//判断是否是数字，不是的话就输入失败
- (void)textFieldChange:(UITextField *)textField
{
    
    if (self.passTf.text.length > 6 || self.passAgainTf.text.length > 6) {
         textField.text = [textField.text stringByReplacingCharactersInRange:NSMakeRange(textField.text.length - 1, 1) withString:@""];
    }
    
    if (self.passTf.text.length > 5 && self.passAgainTf.text.length > 5) {
        self.nextBtn.enabled = YES;
    }else {
        self.nextBtn.enabled = NO;
    }
}
- (void)setUI {
    
    UIView *view = [[UIView alloc] initWithFrame:kScreenB];
    view.backgroundColor = kColorRGB(234, 234, 234);
    [self.view addSubview: view];
    
    UIView *tipBackground = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 30)];
    tipBackground.backgroundColor = kColorRGB(232,213,177);
    [view addSubview:tipBackground];
    
    UILabel *tipLb = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, kScreenW, 30)];
    tipLb.text = @"* 为确保账户资金安全,绑卡前请先设置交易密码";
    tipLb.textColor = kColorRGB(24,24,24);
    tipLb.font = kBaseFont_(12);
    
    [tipBackground addSubview:tipLb];
    
    UITextField *passTf =  [self createTextFieldWithFrame:CGRectMake(0, CGRectGetMaxY(tipLb.frame) + 10, kScreenW, 50) textFont:kBaseFont_(16) textColor:kColorRGB(51, 51, 51) placeholder:@"请输入6位纯数字" placeholderFont:kBaseFont_(13) leftTitle:@"交易密码" delegate:self inView:view tag:100];
    self.passTf = passTf;
    
    UITextField *passAgainTf = [self createTextFieldWithFrame:CGRectMake(0, CGRectGetMaxY(passTf.frame) + 10, kScreenW, 50) textFont:kBaseFont_(16) textColor:kColorRGB(51, 51, 51) placeholder:@"请再次输入交易密码" placeholderFont:kBaseFont_(13) leftTitle:@"确认密码" delegate:self inView:view tag:101];
    self.passAgainTf = passAgainTf;

    UIImage *img = [UIImage imageNamed:@"sure_hieght"];
    UIButton *nextBtn = [[UIButton alloc] initWithFrame:CGRectMake((kScreenW - img.size.width) * 0.5 ,CGRectGetMaxY(passAgainTf.frame) + 38 , img.size.width, img.size.height)];
    [nextBtn setBackgroundImage:img forState:UIControlStateNormal];
    [nextBtn setBackgroundImage:[UIImage imageNamed:@"sure_nor"] forState:UIControlStateDisabled];
    nextBtn.enabled = NO;
    [nextBtn addTarget:self action:@selector(nextBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:nextBtn];
    self.nextBtn = nextBtn;
}

//修改UITextField的placeholder字体并垂直居中
- (NSAttributedString *)textFieldAttributedPlaceholderWith:(UITextField *)textField placeholder:(NSString *)placeholder placeholderFont:(UIFont *)placeholderFont  {
    NSMutableParagraphStyle *style = [textField.defaultTextAttributes[NSParagraphStyleAttributeName] mutableCopy];
    style.minimumLineHeight = textField.font.lineHeight - (textField.font.lineHeight - placeholderFont.lineHeight) / 2.0;
    NSAttributedString *attr = [[NSAttributedString alloc] initWithString:placeholder attributes:@{NSFontAttributeName:placeholderFont, NSParagraphStyleAttributeName : style}];
    return attr;
}

- (UITextField *)createTextFieldWithFrame:(CGRect)frame textFont:(UIFont *)textFont textColor:(UIColor *)textColor placeholder:(NSString *)placeholder placeholderFont:(UIFont *)placeholderFont leftTitle:(NSString *)leftTitle delegate:(id)obj inView:(UIView *)inView tag:(NSInteger)tag {
    
    UITextField *textField = [[UITextField alloc] initWithFrame:frame];
    textField.background = [UIImage imageNamed:@"textfield-1"];
    textField.textAlignment = NSTextAlignmentRight;
    textField.textColor =  textColor;
    textField.font = textFont;
    textField.attributedPlaceholder = [self textFieldAttributedPlaceholderWith:textField placeholder:placeholder placeholderFont:placeholderFont];
    textField.keyboardType = UIKeyboardTypeNumberPad;
//    textField.secureTextEntry = YES;
    [textField addTarget:self action:@selector(textFieldChange:) forControlEvents:UIControlEventEditingChanged];
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 1, 80, 48)];
    leftView.backgroundColor = [UIColor whiteColor];
    
    UILabel *nameLb = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 80, 48)];
    nameLb.text = leftTitle;
    nameLb.textColor = kColorRGB(102,102,102);
    nameLb.font = kBaseFont_(14);
    nameLb.textAlignment = NSTextAlignmentLeft;
    [leftView addSubview:nameLb];
    textField.leftView = leftView;
    textField.leftViewMode = UITextFieldViewModeAlways;
    
    
    UIButton *eyeBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 1, 35, 48)];
    [eyeBtn setImage:[UIImage imageNamed:@"eye"] forState:UIControlStateNormal];
    [eyeBtn setImage:[UIImage imageNamed:@"eyeClose"] forState:UIControlStateSelected];
    eyeBtn.contentMode =  UIViewContentModeLeft;
    textField.rightView = eyeBtn;
    [eyeBtn addTarget:self action:@selector(secureTextEntryClick:) forControlEvents:UIControlEventTouchUpInside];
    eyeBtn.tag = tag;
    textField.rightViewMode = UITextFieldViewModeAlways;
    
    textField.delegate = obj;
    [inView addSubview:textField];
    return textField;
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    
    [self.passTf resignFirstResponder];
    
    [self.passAgainTf resignFirstResponder];
    
    
}



- (void)nextBtnClick:(UIButton *)nextBtn {

    [self requestData];
    
}

- (void)requestData {
    
    NSString *pass = [[self.passTf.text stringByReplacingOccurrencesOfString:@" " withString:@""]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    NSString *passAgain = [[self.passAgainTf.text stringByReplacingOccurrencesOfString:@" " withString:@""]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    if (![pass isEqualToString:passAgain]) {
        [ZHRTRequestFailureShowViewOrDetail showViewDetail:@"两次输入密码不一致" view:self.view];
        self.passTf.text = nil;
        self.passAgainTf.text = nil;
        [self.passTf becomeFirstResponder];
    } else {
        
          NSDictionary * param = @{@"method":@"setSafePass",@"safePassOne":pass,@"safePassTwo":passAgain};
        [AFHTTPSessionManager POSTWithParams:param success:^(NSURLSessionDataTask *task, id responseObject) {
            if ([responseObject[@"code"] isEqualToString:@"100000"]) {
                
                NSUserDefaults *df =   [NSUserDefaults standardUserDefaults] ;
                if ([df valueForKey:@"isChangePass"]) {
                    for (UIViewController *vc in self.navigationController.viewControllers) {
                        if ([vc isKindOfClass:[XDUserCenterController class]]) {
                            NSUserDefaults *df =   [NSUserDefaults standardUserDefaults] ;
                            [df removeObjectForKey:@"isChangePass"];
                            [df synchronize];
                            [self.navigationController popToViewController:vc animated:YES];
                        }
                    }
                } else {
                
                if ([self.delegate respondsToSelector:@selector( sureBtnClcik:)]) {
                    [self.delegate sureBtnClcik:self];
                }else {
                    
               
                NSDictionary * params = @{@"method":@"getAccountStatus"};
                [AFHTTPSessionManager POSTWithParams:params success:^(NSURLSessionDataTask *task, id responseObject) {
                    
                    if ([responseObject[@"code"] isEqualToString:@"100000"]) {
                        NSDictionary *dic = responseObject[@"result"];
                        NSLog(@"%@", dic[@"verifiedStatus"]);
                        if ([dic[@"verifiedStatus"] isEqualToString:@"N"]) {
                            
                            XDVerifiedViewController *verified = [[XDVerifiedViewController alloc] init];
                            
                            [self.navigationController pushViewController:verified animated:YES];
                        } else if ([dic[@"safePassStatus"] isEqualToString:@"N"]) {
                            
                            XDSetSafePassViewController *setSafe = [[XDSetSafePassViewController alloc] init];
                            [self.navigationController pushViewController:setSafe animated:YES];
                            
                        } else if ([dic[@"bindStatus"] isEqualToString:@"N"]) {
                            
                            NSUserDefaults *df = [NSUserDefaults standardUserDefaults];
                            if ([df valueForKey:@"toWithdraw"]) {
                                XDToWithdrawViewController *toWithdraw = [[XDToWithdrawViewController alloc] init];
                                [self.navigationController pushViewController:toWithdraw animated:YES];
                            } else {
                                
                                XDBindBankCardViewController *bindBankCard = [[XDBindBankCardViewController alloc] init];
                                [self.navigationController pushViewController:bindBankCard animated:YES];
                            }
                        
                        }
                    }  else {
                        [ZHRTRequestFailureShowViewOrDetail showViewDetail:responseObject[@"message"] view:self.view];
                    }
                } failure:^(NSURLSessionDataTask *task, NSError *error) {
                    [ZHRTRequestFailureShowViewOrDetail showViewDetail:@"无网络" view:self.view];
                }];
                
                }
                }
            } else if ([responseObject[@"code"] isEqualToString:@"100001"]){ // 超时
                
                
            } else {
                
                [ZHRTRequestFailureShowViewOrDetail showViewDetail:responseObject[@"message"] view:self.view];
            }
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            
        }];
        
    }
    
}

- (void)secureTextEntryClick:(UIButton *)secureBtn {
    
    UIButton *passBtn = [self.view viewWithTag:100];
    UIButton *passAgainBtn = [self.view viewWithTag:101];
    secureBtn.selected = !secureBtn.selected;
    if (secureBtn.selected) {
        self.passTf.secureTextEntry = YES;
        self.passAgainTf.secureTextEntry = YES;
        passBtn.selected = YES;
        passAgainBtn.selected = YES;
    } else {
        self.passTf.secureTextEntry = NO;
        self.passAgainTf.secureTextEntry = NO;
        passBtn.selected = NO;
        passAgainBtn.selected = NO;
    }
    
}

@end
